package com.solution.admin.order.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.solution.admin.order.entity.OrderDeliveredBillEntity;
import com.solution.admin.order.entity.OrderDetailEntity;
import com.solution.admin.order.entity.OrderEntity;
import com.solution.admin.order.entity.OrderLogEntity;
import com.solution.admin.order.entity.OrderProductDeliveredEntity;
import com.solution.admin.order.service.OrderDeliveredBillService;
import com.solution.admin.order.service.OrderService;
import com.solution.admin.product.entity.ProductSpecEntity;
import com.solution.common.constants.PublicStatus;
import com.solution.common.controller.BaseController;
import com.solution.common.page.JSONGrid;
import com.solution.common.page.PageBean;
import com.solution.common.page.PageParam;
import com.solution.common.utils.string.StringUtil;

/**
 * 发货单web控制层
 * @author lilp
 * @date 2017-09-18 22:56:21
 */
@RequestMapping("/orderDeliveredBill")
@Controller
public class OrderDeliveredBillController extends BaseController {

	private Logger logger = LoggerFactory.getLogger(OrderDeliveredBillController.class);

	@Autowired
	private OrderDeliveredBillService orderDeliveredBillService;
	@Autowired
	private OrderService orderService;
	
	/**
	 * 跳转发货单查询页面
	 * @param OrderDeliveredBill 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author lilp
 	 * @date 2017-09-18 22:56:21
	 */
	@RequestMapping("/toListOrderDeliveredBillPage")
	public String toListOrderDeliveredBillPage(OrderDeliveredBillEntity orderDeliveredBill, HttpServletRequest request) {
		return "order/orderDeliveredBill_list";
	}

	/**
	 * 分页查询发货单列表
	 * @param orderDeliveredBill 接收界面查询条件参数
	 * @param request 请求对象
	 * @return 返回对应的页面视图
	 * @author lilp
 	 * @date 2017-09-18 22:56:21
	 */
	@RequestMapping("/listOrderDeliveredBillPage")
	@ResponseBody
	public JSONGrid listOrderDeliveredBillPage(OrderDeliveredBillEntity orderDeliveredBill, HttpServletRequest request){
		int pageNum=Integer.parseInt(request.getParameter("page").toString());
		int numPerPage=Integer.parseInt(request.getParameter("rows").toString());
		PageParam pageParam = super.getPageParam(request);
		pageParam.setPageNum(pageNum);
		pageParam.setNumPerPage(numPerPage);
		
		
		
		Map<String, Object> paramMap = new HashMap<String, Object>();
		try {
			PageBean pageBean = orderDeliveredBillService.listOrderDeliveredBillPage(pageParam, paramMap);
			return new JSONGrid(pageBean.getRecordList(),pageBean.getTotalCount());
		} catch (Exception e) {
			handleException("分页查询发货单失败", logger, e);
		}
		return new JSONGrid();
	}
	

	/**
	 * 查询发货单及已发货的商品清单（发货单明细）
	 * @param request
	 * @return
	 */
	@RequestMapping("/listOrderDetailDelivered")
	@ResponseBody
	public JSONGrid listOrderDetailDelivered(HttpServletRequest request){
		// 订单编号 
		String orderCode = request.getParameter("orderCode");
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("orderCode", orderCode);
		
		try {
			// 查询订单
			Map<Long, OrderDetailEntity>  productMap = new HashMap<Long, OrderDetailEntity>();
			OrderEntity order = null;
			List<OrderEntity> orderList = orderService.listOrder(paramMap);
			if (orderList != null && orderList.size() > 0) {
				order = orderList.get(0);
				if (StringUtil.isNotEmpty(order.getProductDetail())) {
					List<OrderDetailEntity> productList = JSONArray.parseArray(
							"[" + order.getProductDetail() + "]",
							OrderDetailEntity.class);
					order.setProductList(productList);
					for (OrderDetailEntity product : productList) {
						productMap.put(product.getId(), product);
					}
				}
			}
			
			// 查询已发货的商品清单
			List<OrderDeliveredBillEntity> deliveredList = orderDeliveredBillService.listOrderDetailDelivered(paramMap);
			if(deliveredList != null && deliveredList.size() > 0 ){
				for (OrderDeliveredBillEntity product : deliveredList) {
					product.setOrderStatus(order.getOrderStatus());
					if(StringUtil.isNotEmpty(product.getDeliveredProductDetails())){
						List<OrderProductDeliveredEntity>  productList = JSONArray.parseArray("["+product.getDeliveredProductDetails()+"]", OrderProductDeliveredEntity.class);
						List<OrderDetailEntity>  detailList = new ArrayList<OrderDetailEntity>();
						if(productList != null && productList.size() > 0){
							for (OrderProductDeliveredEntity delivredProduct : productList) {
								OrderDetailEntity  tmpDetail = productMap.get(delivredProduct.getDetailId());
								OrderDetailEntity detail = new OrderDetailEntity();
								BeanUtils.copyProperties(detail, tmpDetail);
								detail.setSendNum(delivredProduct.getDeliveredNum());
								
								if(StringUtil.isNotEmpty(detail.getProductSpec())){
									List<ProductSpecEntity> productSpecList = JSONArray.parseArray(detail.getProductSpec(), ProductSpecEntity.class);;
									detail.setProductSpecList(productSpecList);
								}
								detailList.add(detail);
							}
						}
						product.setDeliveredProductList(detailList);
					}
				}
			}
			return new JSONGrid(deliveredList,deliveredList.size());
		} catch (Exception e) {
			handleException("查询订单已发货的商品", logger, e);
		}
		return new JSONGrid();
	}
	
	
	/**
	 * 跳转新增页面
	 * @return string 跳转页面路径
	 * @author lilp
 	 * @date 2017-09-18 22:56:21
	 */
	@RequestMapping("/toAddOrderDeliveredBill")
	public String toAddOrderDeliveredBill(HttpServletRequest request) {
		request.setAttribute("opFlag", "add");
		return "order/orderDeliveredBill_form";
	}

	/**
	 * 跳转编辑页面
	 * @return string 跳转页面路径
	 * @author lilp
 	 * @date 2017-09-18 22:56:21
	 */
	@RequestMapping("/toUpdateOrderDeliveredBill")
	public String toUpdateOrderDeliveredBill(HttpServletRequest request) {
		// 编辑操作
		request.setAttribute("opFlag", "edit");
		long id = Long.valueOf(request.getParameter("id"));
		try {
			OrderDeliveredBillEntity orderDeliveredBill = orderDeliveredBillService.getOrderDeliveredBillById(id);
			request.setAttribute("orderDeliveredBill", orderDeliveredBill);
		} catch (Exception e) {
			handleException("跳转编辑发货单页面错误", logger, e);
		}
		return "order/orderDeliveredBill_form";
	}


	/**
	 * 新增或保存发货单
	 * @param request 请求对象
	 * @param orderDeliveredBillEntity 发货单实体
	 * @return
	 * @author lilp
 	 * @date 2017-09-18 22:56:21
	 */
	@RequestMapping("/saveOrUpdateOrderDeliveredBill")
	@ResponseBody
	public Map<String, Object> saveOrderDeliveredBill(HttpServletRequest request, OrderDeliveredBillEntity orderDeliveredBillEntity) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int result = 0;
		try {
			String id = request.getParameter("id");
			if(StringUtil.isEmpty(id)){
				result = orderDeliveredBillService.updateOrderDeliveredBill(orderDeliveredBillEntity);
			}else{
				result = (int)orderDeliveredBillService.saveOrderDeliveredBill(orderDeliveredBillEntity);
			}
			resultMap.put("code", result);
		} catch (Exception e) {
			handleException("添加发货单失败", logger, e);
		}
		return resultMap;
	}
	
	

	/**
	 * 订单全部发货
	 * @param request 请求对象
	 * @param orderEntity 订单信息实体
	 * @return
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/sendFullOrder")
	@ResponseBody
	public Map<String, Object> sendFullOrder(HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int result = 0;
		Map<String, Object> param = new HashMap<String, Object>();
		// 订单号
		String orderCode = request.getParameter("orderCode");
		// 物流公司ID
		String deliveryCompanyId = request.getParameter("deliveryCompanyCode");
		// 物流单号
		String deliveryCode = request.getParameter("deliveryCode");
		// 备注
		String intro = request.getParameter("intro");
		
		param.put("orderCode", orderCode);
		param.put("deliveryCompanyCode", deliveryCompanyId);
		param.put("deliveryCode", deliveryCode);
		param.put("intro", intro);
		param.put("creater", getUserCode());	//审核人
		//记录日志
		OrderLogEntity orderLog = new OrderLogEntity();
		orderLog.setOrderCode(orderCode);
		orderLog.setOperaterCode(getUserCode());
		orderLog.setOperaterName(getUserName());
		orderLog.setOpTime(new Date());
//		orderLog.setLogType(logType);
		orderLog.setLogContent("订单已发货");
		orderLog.setCreater(getUserName());
		param.put("orderLogEntity", orderLog);
		try {
			result = orderDeliveredBillService.sendFullOrder(param);
			resultMap.put(PublicStatus.RESULT_CODE, result>0?"1":"0");
			resultMap.put(PublicStatus.RESULT_MSG, result>0?"操作成功":"操作失败");
		} catch (Exception e) {
			handleException("商务审核订单", logger, e);
		}
		return resultMap;
	}
	
	
	/**
	 * 订单部分发货
	 * @param request 请求对象
	 * @param orderEntity 订单信息实体
	 * @return
	 * @author lilp
 	 * @date 2017-09-14 23:35:39
	 */
	@RequestMapping("/sendPartOrder")
	@ResponseBody
	public Map<String, Object> sendPartOrder(HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int result = 0;
		Map<String, Object> param = new HashMap<String, Object>();
		
		// 发货商品对应的订单商品详情ids
		String ids = request.getParameter("ids");
		// 发货数量
		String sendNum = request.getParameter("sendNum");
		// 订单详情id
		String detailIds = request.getParameter("detailIds");
		// 订单号
		String orderCode = request.getParameter("orderCode");
		// 物流公司ID
		String deliveryCompanyId = request.getParameter("deliveryCompanyCode");
		// 物流单号
		String deliveryCode = request.getParameter("deliveryCode");
		// 备注
		String intro = request.getParameter("intro");
		
		param.put("orderCode", orderCode);
		param.put("deliveryCompanyCode", deliveryCompanyId);
		param.put("deliveryCode", deliveryCode);
		param.put("intro", intro);
		param.put("creater", getUserCode());	//审核人
		param.put("ids", ids);
		param.put("sendNum", sendNum);
		param.put("detailIds", detailIds);
		//记录日志
		OrderLogEntity orderLog = new OrderLogEntity();
		orderLog.setOrderCode(orderCode);
		orderLog.setOperaterCode(getUserCode());
		orderLog.setOperaterName(getUserName());
		orderLog.setOpTime(new Date());
//		orderLog.setLogType(logType);
		orderLog.setLogContent("订单部分发货");
		orderLog.setCreater(getUserName());
		param.put("orderLogEntity", orderLog);
		try {
			result = orderDeliveredBillService.sendPartOrder(param);
			resultMap.put(PublicStatus.RESULT_CODE, result>0?"1":"0");
			resultMap.put(PublicStatus.RESULT_MSG, result>0?"操作成功":"操作失败");
		} catch (Exception e) {
			handleException("商务审核订单", logger, e);
		}
		return resultMap;
	}
	

	/**
	 * 跳转运单号修改页面
	 * @param request
	 * @return
	 * @author xkl
	 * @date 2018年4月25日 上午11:15:11
	 */
	@RequestMapping("/toModifyDeliverCodeForm")
	public String toModifyDeliverCodeForm(HttpServletRequest request) {
		String id = request.getParameter("id");
		String deliveryCompanyName = request.getParameter("deliveryCompanyName");
		OrderDeliveredBillEntity orderDeliveredBill = orderDeliveredBillService.getOrderDeliveredBillById(Long.parseLong(id));
		request.setAttribute("orderDeliveredBill", orderDeliveredBill);
		request.setAttribute("deliveryCompanyName", deliveryCompanyName);
		return "order/order_deliver_code_form";
	}


	/**
	 * 修改运单号
	 * @param request
	 * @param orderDeliveredBillEntity
	 * @return
	 * @author xkl
	 * @date 2018年4月25日 上午11:15:20
	 */
	@RequestMapping("/modifyDeliverCode")
	@ResponseBody
	public Map<String, Object> modifyDeliverCode(HttpServletRequest request) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		int result = 0;
		try {
			String id = request.getParameter("deliverBillId");
			String deliveryCode = request.getParameter("deliveryCode");
			String deliveryCompanyCode = request.getParameter("deliveryCompanyCode");
			OrderDeliveredBillEntity orderDeliveredBill = new OrderDeliveredBillEntity();
			orderDeliveredBill.setId(Long.parseLong(id));
			orderDeliveredBill.setDeliveryCode(deliveryCode);
			orderDeliveredBill.setDeliveryCompanyCode(deliveryCompanyCode);
			orderDeliveredBill.setModifier(getUserName());
			orderDeliveredBill.setModifyTime(new Date());
			result = orderDeliveredBillService.updateOrderDeliveredBill(orderDeliveredBill);
			resultMap.put(PublicStatus.RESULT_CODE, result>0?"1":"0");
		} catch (Exception e) {
			handleException("修改运单号失败", logger, e);
			resultMap.put("code", 0);
		}
		return resultMap;
	}
}
